<template>
  <el-card class="sourcing-form-card" shadow="never">
    <el-row slot="header" type="flex" justify="space-between" align="middle">
      <span>供应商信息</span>
      <div v-if="!isReadOnly">
        <BtnRender :render="renderBtnsBar" />
      </div>
    </el-row>
    <BasicList
      showActionCol
      :show-select-col="!isReadOnly"
      :tableMaxHeight="300"
      :loading="tableInfo.loading"
      :data-source="tableInfo.list"
      :columns="tableInfo.columns"
      :actionRender="renderTableBtnAction"
      :actionColWidth="140"
      :show-pagination="false"
      :selection-change="handleSelectChange"
    />
    <SupplierDialog
      :dialog-visible="supplierDiaVisible"
      :submitLoading="addSupplierLoading"
      @hide-handler="handleCloseSupplier"
      @add-supplier="handleAddSupplier"
    />
    <PushInquiryDialog
      :pushVisible.sync="pushDialogData.pushVisible"
      :dialog-data="pushDialogData.pushInquiryList"
      :selfPurchaseBillId="selfPurchaseBillId"
      @getSupplierList="getTableData"
    />
    <QuoteDialog
      :quoteVisible.sync="quoteDialogInfo.quoteVisible"
      :isSynergy="quoteDialogInfo.isSynergy"
      :isQuoteDone="quoteDialogInfo.isQuoteDone"
      :isReadOnly="quoteDialogInfo.isReadOnly"
      :sourcingSupplierId="quoteDialogInfo.sourcingSupplierId"
      :selfPurchaseBillId="quoteDialogInfo.selfPurchaseBillId"
      @updateSupplierTableData="getTableData"
    />
    <!-- 修改报价有效期 -->
    <EditExpireTime
      :visible.sync="editExpireTimeVisible"
      :supplierList="tableInfo.selection"
      @getSupplierList="getTableData"
    />
    <!-- 修改报价有效期记录 -->
    <EditExpireTimeRecord
      :visible.sync="editLogVisible"
      :sourcingBillId="selfPurchaseBillId"
    />
  </el-card>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import BasicList from '@/pages/sourcing/components/BasicList'
import SupplierDialog from '@/pages/sourcing/components/SupplierDialog'
import PushInquiryDialog from './components/PushInquiryDialog'
import QuoteDialog from './components/QuoteDialog'
import BtnRender from '@/components/JSXRender/BtnRender';
import EditExpireTime from '@sourcing/components/EditExpireTime';
import EditExpireTimeRecord from '@sourcing/components/EditExpireTimeRecord'
import { getTableAction, getBtnsBar } from '@sourcing/utils/renderBtn';
import {
  queryBillSupplierService,
  addBillSupplierService,
  deleteBillSupplierService,
  finishBillQuoteService
} from '@api/sourcing/selfPurchaseInquiry'
import {
  batchExportSupplierService,
  closeInquiryService
} from '@api/sourcing/purchaseDetail';
import { getSupplierColumns } from '../constants'
import { createExcelByExport } from '@/utils/bizUtils';

export default {
  // 单据供应商信息
  props: ['isReadOnly', 'selfPurchaseBillId'],
  components: {
    BasicList,
    SupplierDialog,
    PushInquiryDialog,
    QuoteDialog,
    BtnRender,
    EditExpireTime,
    EditExpireTimeRecord
  },
  data () {
    return {
      addSupplierLoading: false,
      finishBtnLoading: false,
      supplierDiaVisible: false,
      editExpireTimeVisible: false,
      editLogVisible: false,
      quoteDialogInfo: {
        isSynergy: false,
        isQuoteDone: false,
        quoteVisible: false,
        sourcingSupplierId: '',
        selfPurchaseBillId: null,
      },
      pushDialogData: {
        pushVisible: false,
        pushInquiryList: []
      },
      tableInfo: {
        loading: false,
        list: [],
        columns: getSupplierColumns(),
        selection: []
      },
      batchExportLoading: false,
      batchImportLoading: false,
    }
  },
  watch: {
    selfPurchaseBillId: {
      handler (newVal, oldVal) {
        if (newVal) {
          this.selfPurchaseBillId = newVal;
        }
        this.getTableData()
      },
      immediate: true,
      deep: true
    },
  },
  computed: {
    ...mapState('sourcing/selfPurchase', {
      remark: (state) => state.remark
    }),
    noSelectData () {
      return this.tableInfo.selection.length === 0
    },
    // 已勾选供应商 sourcingSupplierId
    selectedSourcingSupplierIds () {
      return this.tableInfo.selection.map(item => item.sourcingSupplierId)
    },
    // 存在协同供应商
    hasSynergySupplier () {
      return this.tableInfo.selection.some(item => item.onlineCollaboration == 18913)
    }
  },
  methods: {
    ...mapActions('sourcing/purchaseDetail', [
      'getTaxTate', // 获取税率
      'getFreightBearer' // 获取税率
    ]),
    // 获取发票类型 521、税率 10100、运费承担方集合 10146
    queryOptionsAction () {
      this.getTaxTate({
        payload: {
          data: { sysTypeClassId: '10100' }
        }
      });
      this.getFreightBearer({
        payload: {
          data: { sysTypeClassId: '10146' }
        }
      });
    },
    // 表格勾选操作
    handleSelectChange (val) {
      this.tableInfo.selection = val
    },
    async getTableData () {
      const res = await queryBillSupplierService({ selfPurchaseBillId: this.selfPurchaseBillId }, state => { this.tableInfo.loading = state })
      if (res?.data) {
        this.tableInfo.list = res.data
      }
    },
    // 是否为协同供应商 18913为是，18914为否 onlineCollaboration
    isSynergySupplier (type) {
      return type == 18913;
    },
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        {
          label: '修改报价有效期',
          method: this.editQuoteExpireTime,
          type: 'default',
          size: 'mini',
          disabled: this.noSelectData
        },
        {
          label: '报价有效期修改记录',
          method: this.viewEditLog,
          type: 'default',
          size: 'mini',
        },
        {
          label: '批量导出',
          method: this.batchExportSupplierInfo,
          loading: this.batchExportLoading,
          type: 'default',
          size: 'mini',
          disabled: this.noSelectData
        },
        {
          label: '批量导入',
          action: 'srm-api/sourceSupplier/importSupplierAndSkuQuote',
          isImport: true,
          size: 'mini',
          type: 'default',
          loadingFn: state => { this.batchImportLoading = state },
          data: { dataType: 3, billId: this.selfPurchaseBillId }
        },
        { label: '刷新报价状态', type: 'default', size: 'mini', method: this.getTableData },
        { label: '增加供应商', type: 'default', size: 'mini', method: this.handleShowSupplierDialog, },
        { label: '批量推送询价单', type: 'default', size: 'mini', method: () => this.handlePushInquiry(null), disabled: this.noSelectData, },
        { label: '报价完成', type: 'primary', size: 'mini', method: this.handleCompleteQuotation, loading: this.finishBtnLoading, },
      ];
      return getBtnsBar(h, btnsBar);
    },
    // 渲染表格操作栏按钮 未报价 0 报价完成 1 报价中 2 部分报价 3
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '查看', method: () => { this.handleQuotedPrice(row, true) } }]
      if (!this.isReadOnly) {
        // 协同供应商
        if (this.isSynergySupplier(row.onlineCollaboration)) {
          if (row.quoteStatus == 1) {
            actionList.push({ label: '报价', method: () => { this.handleQuotedPrice(row) } })
          }
          if (row.quoteStatus == 0 || row.quoteStatus == 1) {
            actionList.push({ label: '推送询价', method: this.handlePushInquiry })
          }
          if (row.quoteStatus != 2 && row.quoteStatus != 3) {
            actionList.push({ label: '删除', method: this.handleDeleteSupplier })
          }
          if (row.quoteStatus == 2 || row.quoteStatus == 3) {
            actionList.push({ label: '关闭询价单', method: this.handleCloseInquiry })
          }
        } else {
          actionList.push(
            { label: '报价', method: () => { this.handleQuotedPrice(row) } },
            { label: '删除', method: this.handleDeleteSupplier }
          )
        }
      }
      return getTableAction({ h, row, actionList })
    },
    // 修改报价有效期 已过期 协同供应商
    editQuoteExpireTime () {
      if (!this.tableInfo.selection.every(item => item.onlineCollaboration == 18913 && item.quoteStatus == 5)) {
        return this.$message.warning('请勾选报价状态已过期且询价单协同的供应商')
      }
      this.editExpireTimeVisible = true;
    },
    // 查看修改报价有效期记录
    viewEditLog () {
      this.editLogVisible = true;
    },
    // 报价
    handleQuotedPrice (row, isReadOnly) {
      this.queryOptionsAction()
      this.quoteDialogInfo = {
        isSynergy: this.isSynergySupplier(row.onlineCollaboration),
        isQuoteDone: row.quoteStatus == 1, // 报价完成
        quoteVisible: true,
        sourcingSupplierId: row.sourcingSupplierId,
        selfPurchaseBillId: this.selfPurchaseBillId,
        isReadOnly
      }
    },
    // 展示供应商弹框
    handleShowSupplierDialog () {
      if (this.tableInfo.list && this.tableInfo.list.length >= 10) {
        return this.$message.warning('供应商数量最多10个！');
      }
      this.supplierDiaVisible = true;
    },
    handleCloseSupplier () {
      this.supplierDiaVisible = false;
    },
    // 删除供应商
    handleDeleteSupplier (row) {
      this.$confirm('您确定要删除该供应商吗?', '提示', { type: 'warning' })
        .then(() => {
          this.deleteSupplierAction(row);
        })
        .catch(() => {});
    },
    // 关闭询价单
    handleCloseInquiry (row) {
      this.$confirm('关闭询价单后，供应商将无法报价，您确认要提前关闭询价单吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.closeInquiryAction(row.sourcingSupplierId)
        })
        .catch(() => {});
    },
    async closeInquiryAction (sourcingSupplierId) {
      const res = await closeInquiryService(
        { sourcingSupplierId },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        this.$message.success('操作成功')
        this.getTableData()
      }
    },
    // 删除接口调用
    async deleteSupplierAction (row) {
      const data = {
        sourcingSupplierId: row.sourcingSupplierId
      }
      const res = await deleteBillSupplierService(data, state => { this.tableInfo.loading = state })
      if (res) {
        this.$message.success('删除成功')
        this.getTableData()
      }
    },
    // 推送询价单
    handlePushInquiry (row) {
      if (row) {
        this.pushDialogData.pushInquiryList = [row]
      } else {
        const { selection } = this.tableInfo
        this.pushDialogData.pushInquiryList = selection
          .filter(item => (this.isSynergySupplier(item.onlineCollaboration) && (item.quoteStatus == 0 || item.quoteStatus == 1)))
      }
      if (this.pushDialogData.pushInquiryList.length == 0) {
        return this.$message.warning('请勾选未报价的协同供应商。');
      }
      this.pushDialogData.pushVisible = true;
    },
    // 添加供应商
    async handleAddSupplier (param) {
      const data = {
        selfPurchaseBillId: this.selfPurchaseBillId,
        supplierList: param
      }
      const res = await addBillSupplierService(data, state => { this.addSupplierLoading = state })
      if (res) {
        this.$message.success('添加成功')
        this.handleCloseSupplier()
        this.getTableData()
      }
    },
    // 单据报价完成校验
    handleCompleteQuotation () {
      const { list } = this.tableInfo
      if (list.length === 0) {
        return this.$message.warning('供应商数量最少为1个');
      }
      // 不能完成报价状态集合
      const hasNotQuote = list.some(item => [0, 2, 3].includes(item.quoteStatus));
      if (hasNotQuote) {
        return this.$message.warning('存在报价状态为未报价、部分报价、报价中的供应商,不能报价完成');
      }
      this.finishBillQuoteAction();
    },
    // 单据报价完成接口调用
    async finishBillQuoteAction () {
      const { selfPurchaseBillId, remark } = this;
      const param = {
        selfPurchaseBillId,
        remark
      }
      const res = await finishBillQuoteService(param, state => { this.finishBtnLoading = state })
      if (res) {
        this.$message.success('操作成功')
        // 跳转定标页
        this.$router.push({ name: 'selfPurchaseCalibration', query: { selfPurchaseBillId, isCompleteWinBill: '0' } });
      }
    },
    // 批量导出供应商信息
    async batchExportSupplierInfo () {
      if (this.hasSynergySupplier) {
        return this.$message.warning('协同供应商不能导出，请取消勾选');
      }
      const data = {
        billId: this.selfPurchaseBillId,
        dataType: 3,
        sourcingSupplierIdList: this.selectedSourcingSupplierIds
      }
      const res = await batchExportSupplierService(data, state => { this.batchExportLoading = state })
      if (res) {
        createExcelByExport({ res, excelTitle: '供应商信息' });
      }
    },
  }
}
</script>
